package com.djinfo.work.common.baidu.ueditor;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;

/**
 * Created by Administrator on 2016/11/30.
 */
public class PoiHTML {

    public static synchronized String getOnlyId(){
        long curL = System.currentTimeMillis();
        if(curL>curL){
            cacheInt = 0;
        }else{
            cacheInt += 1;
        }
        return String.valueOf(curL)+String.valueOf(cacheInt);

    }
    private static int cacheInt = 0;

    private static long curL = 0;
    // doc转换为html
    public static void docToHtml( String sourceFileName,String targetFileName , String imagePathStr,String imagePath) throws Exception {
        File sourceFile = new File(sourceFileName);
        String randomName = "PIC"+getOnlyId();
        //转换后html中图片src的链接
        final String baseUrl = imagePath+"/"+randomName+"/";
        //转换后图片存放的位置
        String dir = imagePathStr+"/"+randomName+"/";
        File dirF = new File(dir);
        if(!dirF.exists()||!dirF.isDirectory()){
            dirF.mkdir();
        }
        try{
            HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(sourceFile));
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            wordToHtmlConverter.setPicturesManager( new PicturesManager()
            {
                public String savePicture( byte[] content,
                                           PictureType pictureType, String suggestedName,
                                           float widthInches, float heightInches )
                {
                    return baseUrl+suggestedName;
                }
            } );
            wordToHtmlConverter.processDocument(wordDocument);
            List<Picture> pics=wordDocument.getPicturesTable().getAllPictures();
            if(pics!=null){
                for(int i=0;i<pics.size();i++){
                    Picture pic = (Picture)pics.get(i);
                    try {
                        pic.writeImageContent(new FileOutputStream(dir + pic.suggestFullFileName()));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
            Document htmlDocument = wordToHtmlConverter.getDocument();

            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(new File(targetFileName));
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    // docx转换为html
    public static void  docxToHtml( String sourceFileName,String targetFileName , String imagePathStr,String imagePath) throws Exception {
        OutputStreamWriter outputStreamWriter = null;
        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream(sourceFileName));
            XHTMLOptions options = XHTMLOptions.create();
            // 存放图片的文件夹
            options.setExtractor(new FileImageExtractor(new File(imagePathStr)));
            // html中图片的路径
            options.URIResolver(new BasicURIResolver(imagePath));
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(targetFileName), "utf-8");
            XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
            xhtmlConverter.convert(document, outputStreamWriter, options);
        } finally {
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
        }
    }

}